const db = require('../db/index')
const bcrypt = require('bcryptjs')

exports.getInfo = (req, res) => {
  const sql = `select id, username, nickname, email, user_pic
               from ev_users2 
               where id=${req.user.id}
              `
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    if (result.length !== 1) return res.cc('获取信息失败')
    res.send({
      status: 0,
      msg: '获取用户信息成功',
      data: result[0]
    })
  })
}
/*
  为什么token里面的信息要去掉头像
  为什么 更新用户信息不使用 req.user.id 为什么要前端传进来, 
  如果它传进来的id不是当前用户的id呢
*/
exports.updateInfo = (req, res) => {
  const sql = `update ev_users2 set ? where id = ?`
  db.query(sql, [req.body, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('更新用户信息失败')
    res.cc('更新用户信息成功', 0)
  })
}

exports.updatePwd = (req, res) => {
  // 先看一下原密码正确不
  const sql = `select password from ev_users2 where id = ${req.user.id}`
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    if (result.length !== 1) return res.cc('获取原密码失败,稍后再试')
    const compareResult = bcrypt.compareSync(req.body.oldPwd, result[0].password)
    if (!compareResult) return res.cc('原密码错误')
    const newPwd = bcrypt.hashSync(req.body.newPwd, 10)
    const sql = `update ev_users2 set password = "${newPwd}" where id = ${req.user.id}`
    db.query(sql, (err, result) => {
      if (err) return res.send(err)
      if (result.affectedRows !== 1) return res.cc('修改密码失败,稍后再试')
      res.cc('修改密码成功', 0)
    })
  })
}

exports.updateAvatar = (req, res) => {
  const sql = `updata ev_users2 
               set user_pic ="${req.body.avatar}" ? 
               where id = ${req.user.id}`
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('更新头像失败,稍后再试')
    res.cc('更新头像成功', 0)
  })
}